package com.gf.snoopy.controller.resolver;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.gf.snoopy.platform.exception.PokeErrorCode;
import com.gf.snoopy.platform.exception.PokeException;
import com.gf.snoopy.platform.result.PokeResult;

public class ContentExceptionResolver extends SimpleMappingExceptionResolver {

	
	private static final Logger logger = Logger.getLogger(ContentExceptionResolver.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
                                              HttpServletResponse response, Object handler, Exception ex) {

        proccessApiRequest(response,ex);

        return null;
    }

    private void proccessApiRequest(HttpServletResponse response, Exception ex) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain; charset=UTF-8");
        String pokeResult = null;
        if (ex instanceof PokeException) {
        	PokeException pe = (PokeException)ex;
        	pokeResult = PokeResult.getPokeResultFail(pe.getErrorCode(), pe.getErrorMsg());
            logger.warn(ex.getMessage(),ex);
        }else{
        	pokeResult = PokeResult.getPokeResultFail(PokeErrorCode.SYSTEM_ERROR, ex.getMessage());
            logger.error(ex.getMessage(),ex);
        }
        PrintWriter pw = null;
        try {
            String json = pokeResult;
            pw = response.getWriter();
            pw.println(json);
            pw.flush();
        } catch (Exception e) {
        	logger.error(e.getMessage(),e);
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }


}